--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDEROPEN, tonumber('0xFF6633', 16))
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDER, 0xFF6633)
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDERSUB, 0xFF6633)
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDERTAIL, 0xFF6633)
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDEREND, 0xFF6633)
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDEROPENMID, 0xFF6633)
--scite.SendEditor(SCI_MARKERSETFORE, SC_MARKNUM_FOLDERMIDTAIL, 0xFF6633)

--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDEROPEN, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDER, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDERSUB, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDERTAIL, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDEREND, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDEROPENMID, 0x0000FF)
--scite.SendEditor(SCI_MARKERSETBACK, SC_MARKNUM_FOLDERMIDTAIL, 0x0000FF)

--scite.SendEditor(SCI_STYLESETFORE, STYLE_LINENUMBER, 0xFFFF00)
--scite.SendEditor(SCI_STYLESETBACK, STYLE_LINENUMBER, 0xFF00FF)

------------------------------------------------
-- 工具
------------------------------------------------

local snippets = {
    --           0123456789012345678901234567890123456 789012345 678901
    ['for'] = '3;for (%{1} = 0; %{1} < %{2}; %{1}++) {\n    %{3}\n}%{end}',
    ['obj'] = '4;class %{1} {\n    public static function %{2}(%{3}) {\n        %{4}\n    }\n}%{end}',
    ['fcn'] = '3;function %{1}(%{2}) {\n    %{3}\n}%{end}',
    ['form'] = "3;self::load_form();\nif (visitor::is_post()) {\n    $form = new %{1}_form(p());\n    $form->validate();\n    if ($form->is_valid()) {\n        %{3};\n        return;\n    }\n    $form->set_summary('出错了...');\n} else {\n    $form = new %{1}_form();\n}\n$form->set_action_url(url('%{2}', '', '/', false));\nself::set('form', $form);\nself::show();%{end}"
}
local in_snippet
local total_num
local current_num
local begin_pos
local function php_snippet_init()
    in_snippet  = false
    total_num   = 0
    current_num = 0
    begin_pos   = 0
end

------------------------------------------------
-- 事件
------------------------------------------------

function OnChar(c)
    local toClose = {
        ['('] = ')',
        ['['] = ']',
        ['{'] = '}',
        ['"'] = '"',
        ["'"] = "'"
    }
    local toPass = {
        [')'] = '(',
        [']'] = '[',
        ['}'] = '{'
    }
    -- 自动闭合
    if toClose[c] then
        editor:InsertText(editor.CurrentPos, toClose[c])
    end
    -- 智能越过
    if toPass[c] then
        if toPass[c] == string.char(editor.CharAt[editor.CurrentPos - 2]) then
            editor:GotoPos(editor.CurrentPos + 1)
            scite.SendEditor(SCI_DELETEBACK);
        end
    end
end
function OnKey(k, shift, ctrl, alt)
    local toDelete = {
        ['('] = ')',
        ['['] = ']',
        ['{'] = '}',
        ['"'] = '"',
        ["'"] = "'"
    }
    -- 自动删除。8 是回退键
    if k == 8 then
        local pos = editor.CurrentPos - 1
        local chr = editor.CharAt[pos]
        if chr < 0 then
            return
        end
        chr = string.char(chr)
        local mth = string.char(editor.CharAt[pos + 1])
        if toDelete[chr] and toDelete[chr] == mth then
            editor:SetSel(pos, pos + 2)
            editor:ReplaceSel('')
            return true
        end
    -- 回车键
    elseif k == 13 then
        local left_char = editor.CharAt[editor.CurrentPos - 1]
        if left_char < 0 then
            return false
        end
        local left  = string.char(left_char)
        local right = string.char(editor.CharAt[editor.CurrentPos])
        if (left == '{' and right == '}') or
            (left == '(' and right == ')' or
            left == '[' and right == ']') then
            local line = editor:LineFromPosition(editor.CurrentPos)
            scite.SendEditor(SCI_NEWLINE)
            scite.SendEditor(SCI_NEWLINE)
            editor.LineIndentation[line + 2] = editor.LineIndentation[line]
            if left ~= '{' then
                editor.LineIndentation[line + 1] = editor.LineIndentation[line] + 4
            end
            editor:GotoPos(editor.LineEndPosition[line + 1])
            return true
        end
        return false
    -- Tab 键
    elseif k == 9 and in_snippet then
        php_snippet()
        return true
    end
end
function OnUserListSelection(listType, s)
    print(listType, s)
end

------------------------------------------------
-- 命令
------------------------------------------------

function php_snippet()
    if in_snippet then
        current_num = current_num + 1
        if current_num > total_num then
            local b, e = editor:findtext('%{end}', 0, begin_pos)
            editor:SetSel(b, e)
            editor:ReplaceSel('')
            php_snippet_init()
            return
        end
        editor:ClearSelections()
        local str = '%{' .. current_num .. '}'
        local begin = begin_pos
        local end_pos = editor:findtext('%{end}', 0, begin)
        local has_main = false
        -- 寻找所有 str 并选中它
        while true do
            local b, e = editor:findtext(str, 0, begin)
            if b ~= nil then
                if not has_main then
                    editor:SetSelection(b, e)
                    has_main = true
                else
                    editor:AddSelection(b, e)
                end
                begin = e
            else
                break
            end
        end
    else
        local word = props['CurrentWord']
        editor:DelWordLeft()
        total_num     = tonumber(string.sub(snippets[word], 1, 1))
        current_num   = 0
        begin_pos     = editor.CurrentPos
        local curline = scite.SendEditor(SCI_LINEFROMPOSITION, begin_pos)
        local indent  = scite.SendEditor(SCI_GETLINEINDENTATION, curline)
        local snippet = string.sub(snippets[word], 3)
        local lines   = 0
        for i = 1, #snippet do
            local s = string.sub(snippet, i, i)
            if s == '\n' then
                lines = lines + 1
            end
        end
        editor:AddText(snippet)
        for i = 1, lines do
            local line_indent = scite.SendEditor(SCI_GETLINEINDENTATION, curline + i)
            scite.SendEditor(SCI_SETLINEINDENTATION, curline + i, indent + line_indent)
        end
        in_snippet = true
        php_snippet()
    end
end

function php_select_to_quote()
    -- ''  ""
    -- 'abc'  "abc"
    local right_pos = editor.CurrentPos
    local right_chr = string.char(editor.CharAt[right_pos])
    local left_pos  = right_pos - 1
    local left_chr  = string.char(editor.CharAt[left_pos])
    if left_chr == right_chr then
        return false
    end
    if right_chr == '"' or right_chr == "'" then
        editor:SearchAnchor()
        local pos = editor:SearchPrev(0, right_chr) + 1
        editor:SetSel(pos, right_pos)
    end
    if left_chr == '"' or left_chr == "'" then
        editor:SearchAnchor()
        local pos = editor:SearchNext(0, left_chr)
        editor:SetSel(left_pos + 1, pos)
    end
end

--[[
--
-- 从 PHP 打开 TPL
-- action : D:\diogin\code\php\xuniapp\xuniapp\pack\front\main\index.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\view\front\page\main\index.tpl
-- helper : D:\diogin\code\php\xuniapp\xuniapp\view\front\block\header.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\view\front\block\header.tpl
]]--
function php_open_tpl()
    local file_path = props['FilePath']
    local tpl_file  = ''
    if string.find(file_path, '\\pack\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\.php$') ~= nil then
        tpl_file = string.gsub(file_path, '\.php$', '.tpl')
        tpl_file = string.gsub(tpl_file, '\\pack\\([a-z][0-9a-z_]*)\\', '\\view\\%1\\page\\')
    elseif string.find(file_path, '\\view\\[a-z][0-9a-z_]*\\block\\[a-z][0-9a-z_]*\.php$') ~= nil then
        tpl_file = string.gsub(file_path, '\.php$', '.tpl')
    else
        print('no related tpl file')
        return
    end
    scite.Open(tpl_file)
end

--[[
--
-- 从 PHP 打开 CSS
-- action : D:\diogin\code\php\xuniapp\xuniapp\pack\front\main\index.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\site\front\default\page\main\index\css.css
-- helper : D:\diogin\code\php\xuniapp\xuniapp\view\front\block\header.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\site\front\default\block\header\css.css
]]--
function php_open_css()
    local file_path = props['FilePath']
    local css_file  = ''
    if string.find(file_path, '\\pack\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\.php$') ~= nil then
        css_file = string.gsub(file_path, '\.php$', '\\css\.css')
        css_file = string.gsub(css_file, '\\pack\\([a-z][0-9a-z_]*)\\', '\\site\\%1\\default\\page\\')
    elseif string.find(file_path, '\\view\\[a-z][0-9a-z_]*\\block\\[a-z][0-9a-z_]*\.php$') ~= nil then
        css_file = string.gsub(file_path, '\\view\\([a-z][0-9a-z_]*)\\block\\([a-z][0-9a-z_]*)\.php$', '\\site\\%1\\default\\block\\%2\\css.css')
    else
        print('no related css file')
        return
    end
    scite.Open(css_file)
end

--[[
--
-- 从 PHP 打开 JavaScript
-- action : D:\diogin\code\php\xuniapp\xuniapp\pack\front\main\index.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\site\front\default\page\main\index\js.js
-- helper : D:\diogin\code\php\xuniapp\xuniapp\view\front\block\header.php
--       -> D:\diogin\code\php\xuniapp\xuniapp\site\front\default\block\header\js.js
]]--
function php_open_js()
    local file_path = props['FilePath']
    local js_file  = ''
    if string.find(file_path, '\\pack\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\\[a-z][0-9a-z_]*\.php$') ~= nil then
        js_file = string.gsub(file_path, '\.php$', '\\js\.js')
        js_file = string.gsub(js_file, '\\pack\\[a-z][0-9a-z_]*\\', '\\site\\%1\\default\\page\\')
    elseif string.find(file_path, '\\view\\[a-z][0-9a-z_]*\\block\\[a-z][0-9a-z_]*\.php$') ~= nil then
        js_file = string.gsub(file_path, '\\view\\([a-z][0-9a-z_]*)\\block\\([a-z][0-9a-z_]*)\.php$', '\\site\\%1\\default\\block\\%2\\js.js')
    else
        print('no related js file')
        return
    end
    scite.Open(js_file)
end
